<?php

namespace app\admin\controller;

use app\admin\middleware\CheckAdmin;
use app\BaseController;
use app\common\BusinessException;
use app\common\Token;
use think\facade\Db;

class Admin extends BaseController
{
    // 检查登录
    protected $middleware = [
        CheckAdmin::class => ['except' => ['login']],
    ];

    protected $noNeedLogin = ['login'];

    public function index()
    {
        // 获取当前登录用户的信息
        $uid = $this->request->uid;

        $admin = Db::name('admin')->where('id', $uid)->find();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '用户不存在']);
        }

        $role = Db::name('role')->where('id', $admin['roleId'])->find();
        if (!$role) {
            return json(['code' => 401, 'msg' => '角色不存在']);
        }

        // 关联查询出role的所有权限
        $permissions = Db::name('role')
            ->alias('r')
            ->join('rolepermission rp', 'r.id = rp.roleId')
            ->join('permission p', 'rp.permissionId = p.id')
            ->where('r.id', $role['id'])
            ->field('p.*')
            ->select();

        return json(['code' => 200, 'msg' => '获取成功', 'data' => [
            'admin' => $admin,
            'role' => $role,
            'permissions' => $permissions,
        ]]);
    }

    public function create()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $password = password_hash($password, PASSWORD_DEFAULT);

        // 校验参数
        $admin = Db::name('admin')->where('username', $username)->find();
        if ($admin) {
            throw new BusinessException('用户名已存在');
        }

        // 校验密码
        if (strlen($password) < 6) {
            throw new BusinessException('密码长度不能小于6位');

        }

        $result = Db::name('admin')->insert([
            'username' => $username,
            'password' => $password,
            'avatar' => "",
            "nickname" => "",
            "email" => "",
            "roleId" => 4,
            "status" => 1,
        ]);

        if (!$result) {
            throw new BusinessException('创建失败');
        }

        // 查询最新插入的id
        $id = Db::name('admin')->getLastInsID();

        return json(['code' => 200, 'msg' => '创建成功', 'data' => [
            'id' => $id,
        ]]);
    }

    public function edit()
    {
        $data = $this->request->post();
        $id = $this->request->post('id');
        $username = $this->request->post('username');

        // 校验参数
        $admin = Db::name('admin')->where('id', $id)->find();
        if (!$admin) {
            throw new BusinessException('用户不存在');
        }

        // 校验用户名
        if ($admin['username'] != $username) {
            $admin = Db::name('admin')->where('username', $username)->find();
            if ($admin) {
                throw new BusinessException('用户名已存在');
            }
        }

        // 更新用户信息
        $result = Db::name('admin')->where('id', $id)->update($data);

        if (!$result) {
            throw new BusinessException('更新失败');
        }

        return json(['code' => 200, 'msg' => '更新成功']);
    }

    public function delete()
    {
        $id = $this->request->post('id');

        // 校验参数
        $admin = Db::name('admin')->where('id', $id)->find();
        if (!$admin) {
            throw new BusinessException('用户不存在');
        }

        // 删除用户
        $result = Db::name('admin')->where('id', $id)->delete();

        if (!$result) {
            throw new BusinessException('删除失败');
        }

        return json(['code' => 200, 'msg' => '删除成功']);
    }

    public function setRole()
    {
        $adminId = $this->request->post('adminId');
        $roleId = $this->request->post('roleId');

        // 校验参数
        $role = Db::name('role')->where('id', $roleId)->find();
        if (!$role) {
            throw new BusinessException('角色不存在');
        }

        // 校验用户的角色
        $admin = Db::name('admin')->where('id', $adminId)->find();
        if (!$admin) {
            throw new BusinessException('用户不存在');
        }

        if ($admin['roleId'] == $roleId) {
            throw new BusinessException('不能设置为相同角色');
        }

        // 校验用户的角色是否是管理员
        if ($roleId == 1) {
            throw new BusinessException('不能设置为管理员');
        }

        // 更新用户角色
        $result = Db::name('admin')->where('id', $adminId)->update([
            'roleId' => $roleId,
        ]);

        if (!$result) {
            throw new BusinessException('设置失败');
        }

        return json(['code' => 200, 'msg' => '设置成功']);
    }

    public function login()
    {
        // 获取请求参数
        $username = $this->request->post('username');
        $password = $this->request->post('password');

        // 验证参数
        if (empty($username) || empty($password)) {
            return json(['code' => 401, 'msg' => '参数错误']);
        }

        // 用户名 密码 登录

        $admin = Db::name('admin')->where('username', $username)->find();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '用户名或密码错误']);
        }

        // 验证密码
        $result = password_verify($password, $admin['password']);
        if (!$result) {
            return json(['code' => 401, 'msg' => '用户名或密码错误']);
        }

        // jwt 生成token
        $token = Token::generate([
            'id' => $admin['id'],
        ]);
        // 登录成功，返回token
        return json(['code' => 200, 'msg' => '登录成功', 'token' => $token]);
    }

    public function list()
    {
        // 获取分页参数
        $pageNum = $this->request->get('pageNum', 1);
        $pageSize = $this->request->get('pageSize', 10);

        // 计算偏移量
        $offset = ($pageNum - 1) * $pageSize;

        // 查询总数
        $total = Db::name('admin')->count();

        // 查询列表数据
        $list = Db::name('admin')
            ->order('id', 'desc')
            ->limit($offset, $pageSize)
            ->select();

        // 格式化返回数据
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $total,
                'pageNum' => $pageNum,
                'pageSize' => $pageSize,
                'pages' => ceil($total / $pageSize),
            ],
        ]);
    }
}
